<template>
  <div class="carousel-management">
    <div class="header">
      <h2>轮播图管理</h2>
      <div class="actions">
        <el-button type="primary" @click="addCarousel">添加轮播图</el-button>
        <el-button 
          type="danger" 
          :disabled="!selectedCarousels.length" 
          @click="batchDeleteCarousels">
          批量删除
        </el-button>
      </div>
    </div>
    <el-table 
      :data="carouselList" 
      border 
      style="width: 100%" 
      @row-dragend="handleDragEnd"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="id" label="轮播图ID" width="100"></el-table-column>
      <!-- 修改顺序列，添加可编辑输入框 -->
      <el-table-column prop="order" label="顺序" width="80">
        <template slot-scope="scope">
          <el-input
            v-model.number="scope.row.order"
            type="number"
            @change="updateOrder(scope.row)"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="imageUrl" label="图片" width="120">
        <template slot-scope="scope">
          <img :src="scope.row.imageUrl" alt="轮播图" class="carousel-image" @click="handleImageClick(scope.row)">
        </template>
      </el-table-column>
      <el-table-column prop="linkType" label="链接类型" width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.linkType" @change="updateLinkType(scope.row)">
            <el-option label="站内路由" value="internal"></el-option>
            <el-option label="外部链接" value="external"></el-option>
            <el-option label="无跳转" value="none"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="link" label="链接" width="200">
        <template slot-scope="scope">
          <el-input v-if="scope.row.linkType !== 'none'" v-model="scope.row.link" @change="updateLink(scope.row)"></el-input>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" @change="updateStatus(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column prop="startTime" label="生效开始时间" width="180">
        <template slot-scope="scope">
          <el-date-picker
            v-model="scope.row.startTime"
            type="datetime"
            @change="updateTime(scope.row)"
            placeholder="选择开始时间"
          ></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="endTime" label="生效结束时间" width="180">
        <template slot-scope="scope">
          <el-date-picker
            v-model="scope.row.endTime"
            type="datetime"
            @change="updateTime(scope.row)"
            placeholder="选择结束时间"
          ></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column prop="sizeRatio" label="尺寸比例" width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.sizeRatio" @change="updateSizeRatio(scope.row)">
            <el-option label="16:9" value="16:9"></el-option>
            <el-option label="4:3" value="4:3"></el-option>
            <el-option label="1:1" value="1:1"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="displayPosition" label="展示位置" width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.displayPosition" @change="updateDisplayPosition(scope.row)">
            <el-option label="后台管理首页" value="adminHome"></el-option>
            <el-option label="官网首页" value="officialHome"></el-option>
            <el-option label="论坛首页" value="forumHome"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="danger" @click="deleteCarousel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 图片预览对话框 -->
    <el-dialog :title="previewTitle" :visible.sync="previewVisible" width="70%">
      <img :src="previewImageUrl" alt="轮播图" class="preview-image">
      <div v-if="previewImageInfo">
        <p>链接类型: {{ previewImageInfo.linkType }}</p>
        <p v-if="previewImageInfo.linkType !== 'none'">链接: {{ previewImageInfo.link }}</p>
        <p>生效时间: {{ previewImageInfo.startTime }} - {{ previewImageInfo.endTime }}</p>
        <p>尺寸比例: {{ previewImageInfo.sizeRatio }}</p>
        <p>展示位置: {{ getPositionLabel(previewImageInfo.displayPosition) }}</p>
      </div>
    </el-dialog>
    <!-- 添加表单对话框 -->
    <el-dialog :title="isEdit ? '编辑轮播图' : '添加轮播图'" :visible.sync="formVisible" width="50%">
      <el-form :model="formData" label-width="120px">
        <el-form-item label="图片">
          <el-upload
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="formData.imageUrl" :src="formData.imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="顺序">
          <el-input v-model.number="formData.order" type="number"></el-input>
        </el-form-item>
        <el-form-item label="链接类型">
          <el-select v-model="formData.linkType" @change="updateLinkType(formData)">
            <el-option label="站内路由" value="internal"></el-option>
            <el-option label="外部链接" value="external"></el-option>
            <el-option label="无跳转" value="none"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="链接" v-if="formData.linkType !== 'none'">
          <el-input v-model="formData.link"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="formData.status"></el-switch>
        </el-form-item>
        <el-form-item label="生效开始时间">
          <el-date-picker
            v-model="formData.startTime"
            type="datetime"
            placeholder="选择开始时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="生效结束时间">
          <el-date-picker
            v-model="formData.endTime"
            type="datetime"
            placeholder="选择结束时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="尺寸比例">
          <el-select v-model="formData.sizeRatio">
            <el-option label="16:9" value="16:9"></el-option>
            <el-option label="4:3" value="4:3"></el-option>
            <el-option label="1:1" value="1:1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="展示位置">
          <el-select v-model="formData.displayPosition">
            <el-option label="后台管理首页" value="adminHome"></el-option>
            <el-option label="官网首页" value="officialHome"></el-option>
            <el-option label="论坛首页" value="forumHome"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="formVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'CarouselManagement',
  data() {
    return {
      carouselList: [
        {
          id: 1,
          order: 1,
          imageUrl: require('@/assets/images/轮播图1.png'),
          linkType: 'none',
          link: '',
          status: true,
          startTime: '',
          endTime: '',
          sizeRatio: '16:9',
          displayPosition: 'adminHome'
        },
        {
          id: 2,
          order: 2,
          imageUrl: require('@/assets/images/轮播图2.png'),
          linkType: 'none',
          link: '',
          status: true,
          startTime: '',
          endTime: '',
          sizeRatio: '4:3',
          displayPosition: 'officialHome'
        },
        {
          id: 3,
          order: 3,
          imageUrl: require('@/assets/images/轮播图3.png'),
          linkType: 'none',
          link: '',
          status: true,
          startTime: '',
          endTime: '',
          sizeRatio: '1:1',
          displayPosition: 'forumHome'
        }
      ],
      previewVisible: false,
      previewTitle: '图片预览',
      previewImageUrl: '',
      previewImageInfo: null,
      availablePositions: ['adminHome', 'officialHome', 'forumHome', 'newPosition'],
      selectedCarousels: [],
      nextId: 4,
      isEdit: false,
      formVisible: false, // 确保初始化为false
      formData: {
        id: null,
        order: null,
        imageUrl: '',
        linkType: 'none',
        link: '',
        status: true,
        startTime: '',
        endTime: '',
        sizeRatio: '16:9',
        displayPosition: 'adminHome'
      },
      defaultImages: {
        adminHome: require('@/assets/images/轮播图1.png'),
        officialHome: require('@/assets/images/轮播图2.png'),
        forumHome: require('@/assets/images/轮播图3.png')
      }
    };
  },
  methods: {

    handleSelectionChange(val) {
      this.selectedCarousels = val || []; // 确保即使 val 为 undefined 也能安全处理
    },
    

    addCarousel() {
      this.isEdit = false;
      // 重置表单数据
      this.formData = {
        id: this.nextId,
        order: this.carouselList.length + 1,
        imageUrl: '',
        linkType: 'none',
        link: '',
        status: true,
        startTime: '',
        endTime: '',
        sizeRatio: '16:9',
        displayPosition: 'adminHome'
      };
      this.formVisible = true;
    },

    submitForm() {
      if (!this.formData.imageUrl) {
        this.$message.error('请上传轮播图图片');
        return;
      }
      
      if (this.isEdit) {
        const index = this.carouselList.findIndex(item => item.id === this.formData.id);
        if (index !== -1) {
          this.carouselList.splice(index, 1, { ...this.formData });
        }
      } else {
        this.carouselList.push({ ...this.formData });
        this.nextId++;
      }
      this.formVisible = false;
      this.$message.success(this.isEdit ? '轮播图编辑成功' : '轮播图添加成功');
    },

    handleAvatarSuccess(res, file) {
      this.formData.imageUrl = URL.createObjectURL(file.raw);
      this.$message.success('图片上传成功');
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isPNG = file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return (isJPG || isPNG) && isLt2M;
    },
    
    batchDeleteCarousels() {
      this.$confirm('确定要删除选中的轮播图吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const selectedIds = this.selectedCarousels.map(item => item.id);
        this.carouselList = this.carouselList.filter(
          item => !selectedIds.includes(item.id)
        );
     
        this.carouselList.forEach((item, index) => {
          item.order = index + 1;
        });
        this.selectedCarousels = [];
        this.$message.success(`成功删除${selectedIds.length}个轮播图`);
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    updateOrder(item) {
      const position = item.displayPosition;
      const group = this.carouselList.filter(i => i.displayPosition === position);

      item.order = Math.max(1, Math.min(item.order, group.length));
  
      group.sort((a, b) => a.order - b.order);
      group.forEach((i, index) => {
        i.order = index + 1;
      });
      this.$message.success('顺序更新成功');
    },

    handleImageClick(item) {
      if (item.linkType === 'none') {
        this.previewImageUrl = item.imageUrl;
        this.previewImageInfo = item;
        this.previewVisible = true;
      } else if (item.linkType === 'internal') {
        this.$router.push(item.link);
      } else if (item.linkType === 'external') {
        window.open(item.link, '_blank');
      }
    },
  
    handleDragEnd(draggingRow, dropRow) {
      const dragIndex = this.carouselList.indexOf(draggingRow);
      const dropIndex = this.carouselList.indexOf(dropRow);
      this.carouselList.splice(dragIndex, 1);
      this.carouselList.splice(dropIndex, 0, draggingRow);

     
      const positionGroups = {};
      this.carouselList.forEach(item => {
        if (!positionGroups[item.displayPosition]) {
          positionGroups[item.displayPosition] = [];
        }
        positionGroups[item.displayPosition].push(item);
      });

      Object.values(positionGroups).forEach(group => {
        group.sort((a, b) => this.carouselList.indexOf(a) - this.carouselList.indexOf(b));
        group.forEach((item, index) => {
          item.order = index + 1;
        });
      });

      this.$message.success('顺序更新成功');
    },

    updateLinkType(item) {
      if (item.linkType === 'none') {
        item.link = '';
      }
      this.$message.success('链接类型更新成功');
    },
  
    updateLink(item) {
      this.$message.success('链接更新成功');
    },

    updateStatus(item) {
      this.$message.success('状态更新成功');
    },

    updateTime(item) {
      this.$message.success('时间更新成功');
    },
 
    updateSizeRatio(item) {
      this.$message.success('尺寸比例更新成功');
    },
   
    updateDisplayPosition(item) {
      this.$message.success('展示位置更新成功');
    },
  
    deleteCarousel(item) {
      this.$confirm('确定要删除该轮播图吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const index = this.carouselList.findIndex(i => i.id === item.id);
        if (index !== -1) {
          this.carouselList.splice(index, 1);
     
          this.carouselList.forEach((item, index) => {
            item.order = index + 1;
          });
          this.$message.success('删除成功');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    getPositionLabel(position) {
      const positionMap = {
        adminHome: '后台管理首页',
        officialHome: '官网首页',
        forumHome: '论坛首页'
      };
      return positionMap[position];
    }
  },
  computed: {

    carouselListByPosition() {
      return Object.keys(this.defaultImages).map(position => {
        const configuredItem = this.carouselList.find(item => item.displayPosition === position);
        return configuredItem || {
          imageUrl: this.defaultImages[position],
          displayPosition: position,
          linkType: 'none',
          link: '',
          status: true,
          startTime: '',
          endTime: '',
          sizeRatio: '16:9'
        };
      });
    }
  }
};
</script>

<style scoped>
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.actions {
  display: flex;
  gap: 10px;
}

.carousel-image {
  width: 100px;
  height: 60px;
  cursor: pointer;
}
.preview-image {
  width: 100%;
}
.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 100px;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 100px;
  display: block;
}
</style>